package com.lushu.helpers {
import com.lushu.data.ThumbnailInfo;
import com.lushu.info.ApplicationData;

import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLRequest;

public class ThumbnailReader extends EventDispatcher {
    private static var THUMBNAIL_LIST:Vector.<ThumbnailInfo>;

    private var toLoad_:int = 0;

    public function ThumbnailReader() {
        var XML_URL:String = ApplicationData.BASE_LOCATION + "/" + ApplicationData.THUMBIMG_DIRECTORY + "/discovery.php";
        var myXMLURL:URLRequest = new URLRequest(XML_URL);
        var myLoader:URLLoader = new URLLoader(myXMLURL);
        myLoader.addEventListener("complete", dirListed, false, 0, true);
        THUMBNAIL_LIST = new Vector.<ThumbnailInfo>();
    }

    private function dirListed(event:Event):void {
        var thumbnailString:String = event.target.data;
        if (thumbnailString != "") {
            var thumbnailList:Array = thumbnailString.split(":");
            var thumbnailName:String;
            var currentThumbnail:ThumbnailInfo;
            toLoad_ = thumbnailList.length;
            for (var i:int = 0; i < thumbnailList.length; i++) {
                thumbnailName = thumbnailList[i];
                currentThumbnail = new ThumbnailInfo(thumbnailList[i]);
                THUMBNAIL_LIST.push(currentThumbnail);

                currentThumbnail.addEventListener("thumbnailLoaded", thumbnailLoaded, false, 0, true);
            }
        }
        else {
            dispatchEvent(new Event("allThumbnailLoaded"));
        }
    }

    private function thumbnailLoaded(e:Event):void {
        toLoad_--;
        if (toLoad_ == 0) {
            dispatchEvent(new Event("allThumbnailLoaded"));
        }
    }
}
}